<?php

/**
 * This class manages all HTTP requests concerning children.
 */
class ChildController extends Zend_Controller_Action {

    /**
     * Show all children.
     */
    public function indexAction() 
    {
	$this->listAction();
    }

    /**
     * Show all children.
     */
    public function listAction() 
    {
	$m = new Model_Child;
	$children = $m->listAll();
	$this->view->children = $children;
	$this->view->childrenCount = count($children);
    }

    /**
     * Create a new child.
     * 
     * Without POST data, an empty form is displayed.
     * With valid POST data, the child is persisted and one gets redirected
     * to the listAction.
     * With invalid POST data, the form's values with error messages is displayed.
     */
    public function createAction() 
    {
	$request = $this->getRequest();
	$form = new Application_Form_Child();

	if ($request->isPost()) {
	    if ($form->isValid($request->getPost())) {
		$c = $form->getValues();
		$m = new Model_Child;
		$m->create($c);

		return $this->_helper->redirector('list');
	    }
	}

	$this->view->form = $form;
    }

    /**
     * Update data of an existing child.
     * 
     * URL parameter id<int> is required.
     * 
     * Without POST data, a form is with the child's data is displayed.
     * With valid POST data, the child is persisted and the user is redirected
     * to /child/list.
     * With invalid POST data, the form's values with error messages is displayed.
     */
    public function updateAction() 
    {
	$request = $this->getRequest();
	$id = (int)$request->getParam('id');
	$form = new Application_Form_Child();
	$m = new Model_Child;

	if ($request->isPost()) 
	{
	    if ($form->isValid($request->getPost())) 
	    {
		$c = $form->getValues();
		$c['id'] = $id;
		
		$m->update($c);

		return $this->_helper->redirector('list');
	    }
	}
	else
	{
	    $c = $m->find($id);
	    $form->populate($c);
	}

	$this->view->form = $form;
    }
    
    /**
     * Remove an existing child.
     * 
     * URL parameter id<int> is required. The user is redirected to /child/list
     */
    public function deleteAction() 
    {
	$request = $this->getRequest();
	$id = (int)$request->getParam('id');
	
	$m = new Model_Child;
	$m->delete($id);
	
	return $this->_helper->redirector('list');
    }
}